package comet.web;

import java.io.IOException;

import com.google.api.client.googleapis.GoogleHeaders;
import com.google.api.client.googleapis.GoogleTransport;
import com.google.api.client.googleapis.GoogleUrl;
import com.google.api.client.googleapis.auth.clientlogin.ClientLogin;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpResponseException;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.xml.atom.AtomParser;

public class GoogleDistanceView {

	public static int getTermOccurence(String term) {

		HttpTransport transport = setUpTransport();

		//http://code.google.com/apis/customsearch/v1/overview.html

		//Debug.enableLogging();
		// modify cx=
		// To find the value of the cx parameter, go to Control Panel > Codes tab of your CSE 
		// cx code for inukhuk : 
		// Search engine unique ID: 	015428413876645117217:e_ytiihrv6o 
		// see http://www.google.com/cse/docs/resultsxml.html#cxsp
		GoogleUrl customSearchURL = new 
		GoogleUrl("https://www.googleapis.com/customsearch/v1?key=AIzaSyCHScXhbhfX-6VxAsQkTgDWvGQrInUwF0s" +
				"&cx=015428413876645117217:e_ytiihrv6o&q="+term);

		// create request and attach a query 
		HttpRequest request = transport.buildGetRequest();
		request.url=customSearchURL;

		try {
			HttpResponse result = request.execute();
			// to find out more details about the result format , visit
			// http://www.google.com/cse/docs/resultsxml.html

			result.parseAsString();  // or parseAs( SearchEntry.class);
			System.out.write(result.parseAsString().getBytes());
		} catch (IOException e) {
			e.getMessage();
			e.printStackTrace();
		}

		return 0;
	}


	private static HttpTransport setUpTransport() {
		HttpTransport transport = GoogleTransport.create();
		GoogleHeaders headers = (GoogleHeaders) transport.defaultHeaders;
		headers.setApplicationName("Comet");
		transport.addParser(new AtomParser());  //or JsonCParser()
		headers.gdataVersion = "2";

		ClientLogin authenticator = new ClientLogin();
		authenticator.authTokenType = "cl";
		authenticator.username = "inukhuk.gdac@gmail.com";
		authenticator.password = "gdac2010";
		try {
			authenticator.authenticate(). setAuthorizationHeader( transport);
		} catch (HttpResponseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return transport;
	}
}
